//
//  DiscoverView.swift
//  aishop
//
//  Created by tuguowei on 2025/10/15.
//

import SwiftUI

struct DiscoverView: View {
    @StateObject private var viewModel = DiscoverViewModel()
    @State private var selectedTab = 0 // 0: 推荐, 1: 关注
    @State private var selectedCategoryId = ""
    @State private var showPublishSheet = false
    
    var body: some View {
        NavigationView {
            VStack(spacing: 0) {
                // 顶部导航栏
                TopNavigationView(selectedTab: $selectedTab)
                
                // 分类滑动选择（仅在推荐页显示）
                if selectedTab == 0 {
                    CategoryScrollView(
                        categories: viewModel.categories,
                        selectedCategoryId: $selectedCategoryId
                    )
                }
                
                // 内容区域
                TabView(selection: $selectedTab) {
                    // 推荐页面
                    RecommendContentView(
                        notes: viewModel.recommendNotes,
                        authors: viewModel.recommendAuthors,
                        selectedCategoryId: selectedCategoryId,
                        onRefresh: {
                            await viewModel.loadRecommendData(categoryId: selectedCategoryId)
                        },
                        onLoadMore: {
                            await viewModel.loadMoreRecommendData(categoryId: selectedCategoryId)
                        }
                    )
                    .tag(0)
                    
                    // 关注页面
                    FollowContentView(
                        notes: viewModel.followNotes,
                        onRefresh: {
                            await viewModel.loadFollowData()
                        },
                        onLoadMore: {
                            await viewModel.loadMoreFollowData()
                        }
                    )
                    .tag(1)
                }
                .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
            }
            .navigationBarHidden(true)
            .overlay(
                // 发布按钮
                PublishButton {
                    showPublishSheet = true
                }
                .padding(.trailing, 20)
                .padding(.bottom, 100),
                alignment: .bottomTrailing
            )
            .sheet(isPresented: $showPublishSheet) {
                PublishNoteView()
            }
        }
        .onAppear {
            Task {
                await viewModel.loadInitialData()
            }
        }
        .onChange(of: selectedCategoryId) { categoryId in
            Task {
                await viewModel.loadRecommendData(categoryId: categoryId)
            }
        }
    }
}

// MARK: - 顶部导航视图
struct TopNavigationView: View {
    @Binding var selectedTab: Int
    
    private let tabs = ["推荐", "关注"]
    
    var body: some View {
        HStack(spacing: 0) {
            ForEach(0..<tabs.count, id: \.self) { index in
                Button(action: {
                    selectedTab = index
                }) {
                    VStack(spacing: 8) {
                        Text(tabs[index])
                            .font(.system(size: 16, weight: selectedTab == index ? .semibold : .regular))
                            .foregroundColor(selectedTab == index ? ThemeHelper.shared.getColor() : .gray)
                        
                        Rectangle()
                            .fill(selectedTab == index ? ThemeHelper.shared.getColor() : Color.clear)
                            .frame(height: 2)
                            .frame(width: 30)
                    }
                }
                .frame(maxWidth: .infinity)
            }
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
        .background(Color.white)
    }
}

// MARK: - 分类滑动选择视图
struct CategoryScrollView: View {
    let categories: [CommunityCategory]
    @Binding var selectedCategoryId: String
    
    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 16) {
                // 全部分类
                CategoryButton(
                    title: "全部",
                    isSelected: selectedCategoryId.isEmpty,
                    action: {
                        selectedCategoryId = ""
                    }
                )
                
                ForEach(categories) { category in
                    CategoryButton(
                        title: category.name,
                        isSelected: selectedCategoryId == category.id,
                        action: {
                            selectedCategoryId = category.id
                        }
                    )
                }
            }
            .padding(.horizontal, 16)
        }
        .padding(.vertical, 12)
        .background(Color.white)
    }
}

// MARK: - 分类按钮
struct CategoryButton: View {
    let title: String
    let isSelected: Bool
    let action: () -> Void
    
    var body: some View {
        Button(action: action) {
            Text(title)
                .font(.system(size: 14))
                .foregroundColor(isSelected ? .white : .gray)
                .padding(.horizontal, 16)
                .padding(.vertical, 8)
                .background(
                    RoundedRectangle(cornerRadius: 16)
                        .fill(isSelected ? ThemeHelper.shared.getColor() : Color.gray.opacity(0.1))
                )
        }
    }
}

// MARK: - 推荐内容视图
struct RecommendContentView: View {
    let notes: [CommunityNote]
    let authors: [RecommendAuthor]
    let selectedCategoryId: String
    let onRefresh: () async -> Void
    let onLoadMore: () async -> Void
    
    var body: some View {
        ScrollView {
            LazyVStack(spacing: 16) {
                // 推荐作者（仅在全部分类时显示）
                if selectedCategoryId.isEmpty && !authors.isEmpty {
                    RecommendAuthorsView(authors: authors)
                        .padding(.horizontal, 16)
                }
                
                // 瀑布流笔记内容
                WaterfallLayout(notes: notes, onLoadMore: onLoadMore)
                    .padding(.horizontal, 16)
                
                // 底部间距
                Spacer(minLength: 100)
            }
        }
        .refreshable {
            await onRefresh()
        }
    }
}

// MARK: - 关注内容视图
struct FollowContentView: View {
    let notes: [CommunityNote]
    let onRefresh: () async -> Void
    let onLoadMore: () async -> Void
    
    var body: some View {
        ScrollView {
            LazyVStack(spacing: 16) {
                WaterfallLayout(notes: notes, onLoadMore: onLoadMore)
                    .padding(.horizontal, 16)
                
                Spacer(minLength: 100)
            }
        }
        .refreshable {
            await onRefresh()
        }
    }
}

// MARK: - 推荐作者视图
struct RecommendAuthorsView: View {
    let authors: [RecommendAuthor]
    
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            Text("推荐作者")
                .font(.headline)
                .fontWeight(.semibold)
            
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 12) {
                    ForEach(authors) { author in
                        AuthorCardView(author: author)
                    }
                }
                .padding(.horizontal, 4)
            }
        }
        .padding(16)
        .background(Color.white)
        .cornerRadius(12)
    }
}

// MARK: - 作者卡片视图
struct AuthorCardView: View {
    let author: RecommendAuthor
    @State private var isFollowing = false
    
    var body: some View {
        VStack(spacing: 8) {
            AsyncImage(url: URL(string: author.authorAvatar)) { image in
                image
                    .resizable()
                    .aspectRatio(contentMode: .fill)
            } placeholder: {
                Circle()
                    .fill(Color.gray.opacity(0.3))
            }
            .frame(width: 50, height: 50)
            .clipShape(Circle())
            
            Text(author.authorName)
                .font(.caption)
                .fontWeight(.medium)
                .lineLimit(1)
            
            Button(action: {
                Task {
                    await followAuthor()
                }
            }) {
                Text(isFollowing ? "已关注" : "关注")
                    .font(.caption)
                    .foregroundColor(isFollowing ? .gray : .white)
                    .padding(.horizontal, 12)
                    .padding(.vertical, 4)
                    .background(
                        RoundedRectangle(cornerRadius: 12)
                            .fill(isFollowing ? Color.gray.opacity(0.2) : ThemeHelper.shared.getColor())
                    )
            }
        }
        .frame(width: 80)
        .onAppear {
            isFollowing = author.isConcerned
        }
    }
    
    private func followAuthor() async {
        // 调用关注API
        do {
            let response: APIResponse<Bool> = try await APIService.shared.followAuthor(authorId: author.authorId)
            if response.status == 200 {
                isFollowing.toggle()
            }
        } catch {
            print("关注失败: \(error)")
        }
    }
}

// MARK: - 发布按钮
struct PublishButton: View {
    let action: () -> Void
    
    var body: some View {
        Button(action: action) {
            Image(systemName: "plus")
                .font(.system(size: 20, weight: .semibold))
                .foregroundColor(.white)
                .frame(width: 50, height: 50)
                .background(
                    Circle()
                        .fill(ThemeHelper.shared.getColor())
                        .shadow(color: .black.opacity(0.2), radius: 4, x: 0, y: 2)
                )
        }
    }
}

// MARK: - 发布笔记视图（占位符）
struct PublishNoteView: View {
    @Environment(\.dismiss) private var dismiss
    
    var body: some View {
        NavigationView {
            VStack {
                Text("发布笔记功能开发中...")
                    .foregroundColor(.gray)
                    .padding()
                
                Spacer()
            }
            .navigationTitle("发布笔记")
            .navigationBarTitleDisplayMode(.inline)
            .navigationBarBackButtonHidden(true)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("取消") {
                        dismiss()
                    }
                }
            }
        }
    }
}

struct DiscoverView_Previews: PreviewProvider {
    static var previews: some View {
        DiscoverView()
    }
}